package logic

import (
	"context"
	"course-admin/cache"
	"course-admin/model"
	"course-admin/pkg"
	"errors"

	"course-admin/userrpc/internal/svc"
	"course-admin/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 重置密码
func (l *UpdatePasswordLogic) UpdatePassword(in *userrpc.UpdatePasswordRequest) (*userrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var findUser model.User

	if err := findUser.FindUserByMobile(model.DB, in.Mobile); err != nil {
		return nil, err
	}
	if findUser.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	result, _ := cache.Rdb.Get(l.ctx, "sandCode"+in.Mobile).Result()
	if result == "" {
		return nil, errors.New("请发送验证码")
	}
	if result != in.SandCode {
		return nil, errors.New("验证码错误")
	}
	findUser.Password = pkg.Str(in.Password)
	if err := findUser.UpdatePassword(model.DB, in.Password); err != nil {
		return nil, errors.New("修改失败")
	}
	return &userrpc.UpdatePasswordResponse{
		UserId: int64(findUser.ID),
	}, nil
}
